import {messages} from "share/common";
import React from 'react'
import { connect } from 'react-redux'
import { Form, Input, Switch, Button, Icon, Checkbox, Alert, message } from 'antd'
const FormItem = Form.Item;
const { TextArea } = Input;

import scenariosService from 'containers/budget-setting/budget-organization/budget-scenarios/budget-scenarios.service'
import 'styles/budget-setting/budget-organization/budget-scenarios/update-budget-scenarios.scss'
import { LanguageInput } from 'components/template';

class UpdateBudgetScenarios extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      params: {},
      isEnabled: true,
      loading: false,
      i18n: props.params.i18n || {},
    };
  }

  componentDidMount(){
    this.setState({
      params: this.props.params,
      isEnabled: this.props.params.isEnabled
    })
  }

  componentWillReceiveProps(nextProps){
    if (!nextProps.params.hasInit) {
      nextProps.params.hasInit = true;
      this.setState({
        params: nextProps.params,
        isEnabled: nextProps.params.isEnabled
      }, () => {
        this.props.form.resetFields()
      })
    }
  }

  handleSave = (e) =>{
    const { i18n, description, scenarioName } = this.state;
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        values.defaultFlag = (values.defaultFlag === null ? false : values.defaultFlag);
        if (values.defaultFlag && !values.isEnabled) {
          message.error(messages('budget-setting.key138'/*默认预算场景的状态必须为启用*/));
          return;
        }
        values.organizationId = this.state.params.organizationId;
        values.id = this.state.params.id;
        values.versionNumber = this.state.params.versionNumber;
        this.setState({loading: true});
        scenariosService.updateScenarios({ ...values, ...{ i18n, description, scenarioName } })
          .then((res) => {
            if (res.status === 200) {
              this.state.params.versionNumber++;
              this.props.close(true);
              message.success(messages('common.save.success', { name: '' })/*保存成功*/);
            }
          })
          .catch((e) => {
            if (e.response) {
              message.error(`${messages('common.save.filed')/*保存失败*/}, ${e.response.data.message}`);
            }
          })
          .finally(() => {
            this.setState({ loading: false });
          });
      }
    });
  };

  onCancel = () =>{
    this.props.close();
  };

  switchChange = () => {
    this.setState((prevState) => ({
      isEnabled: !prevState.isEnabled
    }))
  };

  handleI18n = (name, value, tag) => {
    let { i18n, scenarioName, description } = this.state;
    if (tag === 'input') {
      i18n.scenarioName = value;
      scenarioName = name;
    } else {
      i18n.description = value;
      description = name;
    }
    this.setState({ scenarioName, description, i18n });
  };

  render(){
    const { getFieldDecorator } = this.props.form;
    const { params, isEnabled, loading, i18n, scenarioName, description } = this.state;
    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 14, offset: 1 },
    };
    return (
      <div className="update-budget-scenarios">
        <Alert message={messages('common.help')/*帮助提示*/}
               description={messages('budget-setting.key139'/*预算组织为当前用户所在账套下的生效的预算组织，同一账套下预算场景代码不允许重复，一个预算组织下允许多个预算场景同时生效。*/)}
               type="info" showIcon />
        <Form onSubmit={this.handleSave}>
          <FormItem {...formItemLayout} label={messages('budget-setting.key47'/*预算组织*/)}>
            {getFieldDecorator('organizationName', {
              rules: [{
                required: true
              }],
              initialValue: params.organizationName
            })(
              <Input disabled className="input-disabled-color"/>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label={messages('budget-setting.key133'/*预算场景代码*/)}>
            {getFieldDecorator('scenarioCode', {
              rules: [{
                required: true
              }],
              initialValue: params.scenarioCode
            })(
              <Input disabled className="input-disabled-color"/>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label={messages('budget-setting.key134'/*预算场景名称*/)}>
            {getFieldDecorator('scenarioName', {
              rules: [{
                required: true,
                message: messages('common.please.enter')/*请输入*/
              }],
              initialValue: params.scenarioName
            })(
              <LanguageInput
                name={scenarioName}
                isEdit
                i18nName={i18n.scenarioName || null}
                nameChange={(name, scenarioName) => this.handleI18n(name, scenarioName, 'input')}
                placeholder={messages('common.please.enter')/* 请输入 */}/>)}
          </FormItem>
          <FormItem {...formItemLayout} label={messages('common.remark')/*备注*/}>
            {getFieldDecorator('description', {
              initialValue: params.description
            })(
              <LanguageInput
                name={description}
                isEdit
                textArea
                i18nName={i18n.description || null}
                nameChange={(name, description) => this.handleI18n(name, description, 'textArea')}
                placeholder={messages('common.please.enter')/* 请输入 */}/>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label={messages('common.column.status')/*状态*/}>
            {getFieldDecorator('isEnabled', {
              valuePropName: "checked",
              initialValue: isEnabled
            })(
              <Switch checkedChildren={<Icon type="check"/>}
                      unCheckedChildren={<Icon type="cross" />}
                      onChange={this.switchChange}/>
            )}
            <span className="enabled-type">
              {isEnabled ? messages('common.status.enable')/*启用*/ : messages('common.status.disable')/*禁用*/}
            </span>
          </FormItem>
          <FormItem {...formItemLayout} label={messages('budget-setting.key140'/*是否默认*/)}>
            {getFieldDecorator('defaultFlag', {
              valuePropName: "checked",
              initialValue: params.defaultFlag
            })(
              <Checkbox />
            )}
          </FormItem>
          <div className="slide-footer">
            <Button type="primary" htmlType="submit" loading={loading}>{messages('common.save')/*保存*/}</Button>
            <Button onClick={this.onCancel}>{messages('common.cancel')/*取消*/}</Button>
          </div>
        </Form>
      </div>
    )
  }
}

function mapStateToProps(state) {
  return {}
}

const WrappedUpdateBudgetScenarios = Form.create()(UpdateBudgetScenarios);

export default connect(mapStateToProps)(WrappedUpdateBudgetScenarios);

